﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseEnumConverter.xaml.cs" company="R.V.Kasner">
//   Copyright © 2011 R.V.Kasner
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Owen.Terminal.View.Converters
{
    using System;
    using System.Globalization;
    using System.Windows.Data;

    public abstract class BaseEnumConverter<TEnum> : IValueConverter
    {
        private readonly Tuple<TEnum, string>[] convertValues;

        protected BaseEnumConverter(Tuple<TEnum, string>[] convertValues)
        {
            this.convertValues = convertValues;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is TEnum) return this.FindString((TEnum)value);

            if (value is TEnum[])
            {
                var array = value as TEnum[];
                var result = new string[array.Length];
                for (var i = 0; i < array.Length; i++)
                {
                    result[i] = this.FindString(array[i]);
                }

                return result;
            }

            throw new ArgumentException("Неподдерживаемый тип: " + value + "[" + value.GetType() + "]");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string[]) throw new ArgumentException("Не поддерживается преобразование из массива строк.");

            return this.FindEnum((string)value);
        }

        private TEnum FindEnum(string str)
        {
            foreach (var tuple in this.convertValues)
            {
                if (tuple.Item2 == str) return tuple.Item1;
            }

            throw new ArgumentException("Не найдено значение для строки: " + str);
        }

        private string FindString(TEnum db)
        {
            foreach (var tuple in this.convertValues)
            {
                if (tuple.Item1.Equals(db)) return tuple.Item2;
            }

            return db.ToString();
        }
    }
}